<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth' // 引入 Pinia store

// 获取 Pinia store
const authStore = useAuthStore();

// 表单数据
const username = ref('');
const password = ref('');
const rememberPassword = ref(true); // 记住密码选项

const changeRmemberPassword = () => {
  rememberPassword.value = !rememberPassword.value;
}

// 登录函数
const doLogin = async () => {
  try {
    const success = await authStore.login(username.value, password.value)
    console.log('登录结果:', success.isLoggedIn)
    if (success) {
      // 如果选择了记住密码，可以将用户名保存到 localStorage
      if (rememberPassword.value) {
        uni.setStorageSync('rememberedUsername', username.value);
        uni.setStorageSync('rememberedPassword', password.value);
        uni.setStorageSync('userInfo', JSON.stringify(success.user));
      } else {
        // 清除本地存储
        uni.removeStorageSync('rememberedUsername');
        uni.removeStorageSync('rememberedPassword');
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
      }

      // uni.reLaunch({
      //   url: '/pages/index/index', // 重定向到首页
      // })
      //跳转回首页
      uni.switchTab({
        url: '/pages/index/index' // 确保此路径是 tabBar 中定义的一个页面
      });
    }
  } catch (error) {
    console.error('登录失败:', error)
    // 显示错误提示
    uni.showToast({
      title: '登录失败，请检查用户名和密码',
      icon: 'none',
      duration: 2000,
    })
  }
}

// 使用 watch 监听 password 的变化
// watch(showPassword, (newVal: boolean, oldVal: boolean) => {
//   console.log(`password change from ${oldVal} to ${newVal}`)
// })

// 注册按钮点击事件
const doRegister = () => {
  // 这里可以跳转到注册页面
  uni.navigateTo({
    url: '/pages/register/register',
  })
}

// 使用 onMounted 确保初始化时检查存储中有无记住的用户名
onMounted(() => {
  if (typeof wx !== 'undefined' && uni.getStorageSync) {
    const rememberedUsername = uni.getStorageSync('rememberedUsername') || '';

    if (rememberedUsername !== '') {
      username.value = rememberedUsername;
      password.value = uni.getStorageSync('rememberedPassword');
      doLogin();
    }

  } else {
    // 显示错误提示
    uni.showToast({
      title: '不在微信环境中，无法获取用户信息', // 显示错误提示
      icon: 'none',
      duration: 2000,
    })
  }
})


// 定义数据
// const value = ref('');
// 输入框输入事件处理
// const input = (event: Event) => {
//   const target = event.target as HTMLInputElement;
//   value.value = target.value;
//   console.log('输入内容：', target.value);
// };

// 使用 ref 创建响应式变量，并指定其类型
const value = ref<string>('');

// 定义 input 处理函数，明确 event 参数的类型
const input = (event: Event) => {
  // 检查 event 和 event.target 是否存在，并断言 event.target 是 HTMLInputElement 类型
  const target = event.target as HTMLInputElement | null;
  if (!target || !(target instanceof HTMLInputElement)) {
    console.error('Invalid event or target:', event);
    return;
  }

  // 更新 value 的值为当前输入框的值
  value.value = target.value;
  console.log('输入内容：', target.value);
};

</script>

<template>
  <view class="login-container">
    <view class="login-form">
      <view class="h2">登录</view>

      <uni-section>
        <uni-easyinput errorMessage v-model="username" focus placeholder="请输入账号" clearable
          @input="input"></uni-easyinput>
      </uni-section>

      <!-- 账号输入框 -->
      <!-- <input v-model="username" type="text" placeholder="请输入账号" class="input-field" /> -->
      <!-- 密码输入框 -->

      <uni-section>
        <uni-easyinput type="password" v-model="password" placeholder="请输入密码" clearable></uni-easyinput>
      </uni-section>
      <!-- <input v-model="password" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码" class="input-field" /> -->
      <view class="checkbox-container">
        <view class="checkbox-set">
          <!-- <label class="checkbox-label">
            <checkbox :checked="showPassword" @click="changeShowPassword" />
            显示密码
          </label> -->

          <!-- <label>
          显示密码
          <switch :checked="showPassword" @change="changeShowPassword" />
        </label> -->
          <label class="checkbox-label">
            <checkbox :checked="rememberPassword" @click="changeRmemberPassword" />
            是否记住密码
          </label>
        </view>


        <!-- <label
          >记住密码
          <switch :checked="rememberPassword" @change="changerRmemberPassword" />
        </label> -->
      </view>

      <view class="button-container">
        <button @click="doLogin" class="login-button">登录</button>
        <button @click="doRegister" class="register-button">注册</button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.login-container {
  display: flex;
  justify-content: center;
  // align-items: center;
  align-items: flex-start;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-form {
  display: flex;
  flex-wrap: wrap;
  width: 70%; // 调整宽度，使其更适合移动设备
  max-width: 300px; // 最大宽度
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  flex-direction: column;

  margin-top: 5vh;


  .h2 {
    margin-bottom: 20px;
    font-size: 2rem; // 调整标题字体大小
    color: #333;
    align-self: center;
  }

  .input-field {
    width: 100%;
    height: 40px;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 1rem;
    box-sizing: border-box; // 确保内边距和边框不会增加元素的总宽度
  }

  .checkbox-container {
    display: flex;
    justify-content: space-between;
    margin-bottom: 35px;
    font-size: 0.9rem; // 调整复选框字体大小
  }

  .checkbox-set {
    margin-top: 15px;
  }

  .button-container {
    display: flex;
    flex-wrap: wrap;
  }

  .login-button,
  .register-button {
    width: 100px;
    height: 30px;
    padding: 0px;
    background-color: #1890ff;
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 1rem;
    cursor: pointer;
    margin-bottom: 15px;
    line-height: 30px;

    &:hover {
      background-color: #40a9ff;
    }
  }

  .register-button {
    background-color: #28a745;

    &:hover {
      background-color: #218838;
    }
  }
}
</style>
